package com.zhangxin.aiInterview.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangxin.aiInterview.common.ErrorCode;
import com.zhangxin.aiInterview.exception.BusinessException;
import com.zhangxin.aiInterview.manager.work_flow.full_process_interview_analyze.FullProcessInterviewAnalyze;
import com.zhangxin.aiInterview.manager.cos.CosManager;
import com.zhangxin.aiInterview.model.entity.*;
import com.zhangxin.aiInterview.service.*;
import com.zhangxin.aiInterview.mapper.FullProcessInterviewMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ZX
 * @description 针对表【full_process_interview(全流程面试主表)】的数据库操作Service实现
 * @createDate 2025-05-30 14:06:13
 */
@Service
@Slf4j
public class FullProcessInterviewServiceImpl extends ServiceImpl<FullProcessInterviewMapper, FullProcessInterview>
        implements FullProcessInterviewService {

    @Resource
    private FullProcessInterviewAnalyzeResultService fullProcessInterviewAnalyzeResultService;
    @Resource
    private FullProcessAnalyzeResultService fullProcessAnalyzeResultService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    @Lazy
    private ResumeService resumeService;
    @Resource
    private ResumeContentService resumeContentService;
    @Resource
    private ResumeAnalysisResultService resumeAnalysisResultService;
    @Resource
    @Lazy
    private ExamService examService;
    @Resource
    private ExamContentService examContentService;
    @Resource
    private ExamAnalysisResultService examAnalysisResultService;
    @Resource
    @Lazy
    private AiInterviewService aiInterviewService;
    @Resource
    private AiInterviewContentService aiInterviewContentService;
    @Resource
    private AiInterviewAnalyzeResultService aiInterviewAnalyzeResultService;
    @Resource
    @Lazy
    private HrInterviewService hrInterviewService;
    @Resource
    private HrInterviewContentService hrInterviewContentService;
    @Resource
    private HrInterviewAnalyzeResultService hrInterviewAnalyzeResultService;
    @Resource
    private CosManager cosManager;

    /**
     * 全流程分析
     *
     * @param fullProcessInterviewId
     * @return
     */
    @Override
    public Boolean analyzeFullProcessInterviewAnalyze(Long fullProcessInterviewId, HttpServletRequest request) {

        FullProcessInterview fullProcessInterview = getById(fullProcessInterviewId);
        Long resumeId = fullProcessInterview.getResumeId();
        Long userId = fullProcessInterview.getUserId();
        Long examId = fullProcessInterview.getExamId();
        Long aiInterviewId = fullProcessInterview.getAiInterviewId();
        Long hrInterviewId = fullProcessInterview.getHrInterviewId();
        try {
            //调用工作流 进行全流程面试结果分析
            FullProcessInterviewAnalyze.InterviewEvaluation interviewEvaluation = FullProcessInterviewAnalyze.analyzeFullProcessInterviewAnalyze(resumeId, userId, examId, aiInterviewId, hrInterviewId);
            FullProcessInterviewAnalyzeResult fullProcessInterviewAnalyzeResult = BeanUtil.copyProperties(interviewEvaluation, FullProcessInterviewAnalyzeResult.class);
            fullProcessInterviewAnalyzeResult.setUserId(userId);

            //开始事务
            transactionTemplate.execute(status -> {
                //将全流程面试分析结果数据写入数据库
                boolean save = fullProcessInterviewAnalyzeResultService.save(fullProcessInterviewAnalyzeResult);
                if (!save) throw new BusinessException(ErrorCode.OPERATION_ERROR, "保存全流程面试分析结果数据失败");
                //关联全流程面试分析结果id
                boolean update = fullProcessAnalyzeResultService.lambdaUpdate()
                        .eq(FullProcessAnalyzeResult::getFullInterviewId, fullProcessInterviewId)
                        .set(FullProcessAnalyzeResult::getFinalAnalysisId, fullProcessInterviewAnalyzeResult.getId())
                        .update();
                if (!update) throw new BusinessException(ErrorCode.OPERATION_ERROR, "关联全流程面试分析结果数据失败");
                //提交事务
                return true;
            });
            return true;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "全流程分析失败:" + e.getMessage());
        }
    }

    /**
     * 删除全流程面试记录和相关信息
     * @param fullProcessInterviewId
     * @param request
     * @return
     */
    @Override
    public boolean deleteFullProcessInterview(Long fullProcessInterviewId, HttpServletRequest request) {
        //开启方法事务
        transactionTemplate.execute(status -> {
            try {
                // 获取其他流程面试id
                FullProcessInterview fullProcessInterview = getById(fullProcessInterviewId);
                //获取当前步骤
                Integer step = fullProcessInterview.getStep();

                Long resumeId = fullProcessInterview.getResumeId();
                Long examId = fullProcessInterview.getExamId();
                Long aiInterviewId = fullProcessInterview.getAiInterviewId();
                Long hrInterviewId = fullProcessInterview.getHrInterviewId();

                //获取简历链接
                String resumeUrl = resumeService.getById(resumeId).getResumeUrl();
                String regex = "^https://zx-1343343346\\.cos\\.ap-chongqing\\.myqcloud\\.com/(.*)$";

                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(resumeUrl);

                if (matcher.find()) {
                    resumeUrl = matcher.group(1);
                } else {
                    System.out.println("URL 不匹配指定的格式");
                }

                if (step == 0){
                    //删除简历相关分析
                    resumeService.removeById(resumeId);

                    resumeContentService.lambdaUpdate()
                            .eq(ResumeContent::getResumeId, resumeId)
                            .remove();

                    resumeAnalysisResultService.lambdaUpdate()
                            .eq(ResumeAnalysisResult::getResumeId, resumeId)
                            .remove();

                    //删除简历
                    cosManager.deleteObject(resumeUrl);
                    log.info("删除简历成功：" + resumeUrl);
                }else if (step == 1) {
                    //删除简历相关分析
                    resumeService.removeById(resumeId);

                    resumeContentService.lambdaUpdate()
                            .eq(ResumeContent::getResumeId, resumeId)
                            .remove();

                    resumeAnalysisResultService.lambdaUpdate()
                            .eq(ResumeAnalysisResult::getResumeId, resumeId)
                            .remove();

                    //删除简历
                    cosManager.deleteObject(resumeUrl);
                    log.info("删除简历成功：" + resumeUrl);

                    examService.removeById(examId);

                    examContentService.lambdaUpdate()
                            .eq(ExamContent::getExamId, examId)
                            .remove();

                    examAnalysisResultService.lambdaUpdate()
                            .eq(ExamAnalysisResult::getExamId, examId)
                            .remove();
                } else if (step == 2) {
                    //删除简历相关分析
                    resumeService.removeById(resumeId);

                    resumeAnalysisResultService.lambdaUpdate()
                            .eq(ResumeAnalysisResult::getResumeId, resumeId)
                            .remove();

                    resumeContentService.lambdaUpdate()
                            .eq(ResumeContent::getResumeId, resumeId)
                            .remove();

                    //删除简历
                    cosManager.deleteObject(resumeUrl);
                    log.info("删除简历成功：" + resumeUrl);

                    examService.removeById(examId);

                    examContentService.lambdaUpdate()
                            .eq(ExamContent::getExamId, examId)
                            .remove();

                    examAnalysisResultService.lambdaUpdate()
                            .eq(ExamAnalysisResult::getExamId, examId)
                            .remove();

                    aiInterviewService.removeById(aiInterviewId);

                    aiInterviewContentService.lambdaUpdate()
                            .eq(AiInterviewContent::getAiInterviewId, aiInterviewId)
                            .remove();

                    aiInterviewAnalyzeResultService.lambdaUpdate()
                            .eq(AiInterviewAnalyzeResult::getAiInterviewId, aiInterviewId)
                            .remove();
                } else{
                    //删除简历相关分析
                    resumeService.removeById(resumeId);

                    resumeContentService.lambdaUpdate()
                            .eq(ResumeContent::getResumeId, resumeId)
                            .remove();

                    resumeAnalysisResultService.lambdaUpdate()
                            .eq(ResumeAnalysisResult::getResumeId, resumeId)
                            .remove();

                    //删除简历
                    cosManager.deleteObject(resumeUrl);
                    log.info("删除简历成功：" + resumeUrl);

                    examService.removeById(examId);

                    examContentService.lambdaUpdate()
                            .eq(ExamContent::getExamId, examId)
                            .remove();

                    examAnalysisResultService.lambdaUpdate()
                            .eq(ExamAnalysisResult::getExamId, examId)
                            .remove();

                    aiInterviewService.removeById(aiInterviewId);

                    aiInterviewContentService.lambdaUpdate()
                            .eq(AiInterviewContent::getAiInterviewId, aiInterviewId)
                            .remove();

                    aiInterviewAnalyzeResultService.lambdaUpdate()
                            .eq(AiInterviewAnalyzeResult::getAiInterviewId, aiInterviewId)
                            .remove();

                    hrInterviewService.removeById(hrInterviewId);

                    hrInterviewContentService.lambdaUpdate()
                            .eq(HrInterviewContent::getHrInterviewId, hrInterviewId)
                            .remove();

                    hrInterviewAnalyzeResultService.lambdaUpdate()
                            .eq(HrInterviewAnalyzeResult::getHrInterviewId, hrInterviewId)
                            .remove();
                }

                // 删除全流程面记录
                removeById(fullProcessInterviewId);

                //查询全流程分析报告id
                FullProcessAnalyzeResult fullProcessAnalyzeResult = fullProcessAnalyzeResultService.lambdaQuery()
                        .eq(FullProcessAnalyzeResult::getFullInterviewId, fullProcessInterviewId)
                        .select(FullProcessAnalyzeResult::getFinalAnalysisId)
                        .one();

                // 删除全流程面试分析中间表
                fullProcessAnalyzeResultService.lambdaUpdate()
                        .eq(FullProcessAnalyzeResult::getFullInterviewId, fullProcessInterviewId)
                        .remove();

                // 删除全流程面试分析报告
                if (ObjUtil.isEmpty(fullProcessAnalyzeResult)) return null;
                Long finalAnalysisId = fullProcessAnalyzeResult.getFinalAnalysisId();
                fullProcessInterviewAnalyzeResultService.removeById(finalAnalysisId);

            } catch (Exception e) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除全流程面记录相关信息失败，id为:"+fullProcessInterviewId+"，报错信息" + e.getMessage());
            }
            return null;
        });
        return true;
    }
}